<template>
  <div class="container">
    <!-- loading页 -->
    <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" size="50" />
    <!-- 正文 -->
    <template v-else>
      <van-sticky>
        <div class="sticky-content">
          <!-- 顶部自定义搜索框 -->
          <SearchBar :keyword="artistKeyword" :currentPosition="currentPosition" />
          <!-- 顶部分类 -->
          <div class="categories">
            <div class="category" v-for="(category, index) in categories" :key="index"
              @click="goToCategory(category.id, index)">
              <van-image :src="category.imgUrl" width="22" height="22"></van-image>
              <p>{{ category.title }}</p>
            </div>
          </div>
        </div>
      </van-sticky>

      <!-- banner -->
      <div class="banner-wrapper">
        <div class="banner">
          <swiper @swiper="onSwiper" :spaceBetween="10" :modules="modules"
            :pagination="{ clickable: false, dynamicBullets: true }" @slideChange="onSlideChange">
            <template v-for="(banner, index) in banners" :key="index">
              <swiper-slide><img :src="banner.imgUrl" class="thumb" /></swiper-slide>
            </template>
          </swiper>
        </div>
      </div>

      <!-- 热门巡演 -->

      <PopularTours :popularTours="popularTours" />

      <!-- 折扣尾票 -->
      <Discount :disCounts="disCounts" />

      <!-- 为你推荐 -->
      <Recommend />

      <!-- 底部导航 -->
      <tab-bar />

      <!-- 广告弹窗 -->
      <Dialog :showPopUpAd="showPopUpAd" @toggle:dialog="closeDialog" />
    </template>
  </div>
</template>

<script setup>
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue'

import { Pagination } from 'swiper/modules'

// Import Swiper styles
import 'swiper/css'
import 'swiper/css/pagination'

import SearchBar from '@/component/common/SearchBar.vue'
import PopularTours from '@/component/home/PopularTours.vue'
import Discount from '@/component/home/Discount.vue'
import Recommend from '@/component/home/Recommend.vue'
import Dialog from '@/component/home/Dialog.vue'
import TabBar from '@/component/common/TabBar.vue'

import { ref, onMounted, computed, reactive } from 'vue'
import { fetchLocation, fetchSearchHot, fetchHomeData } from '@/api/index.js'
import { useStore } from '@/stores/index'
const store = useStore() //store 实例
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()

/* 变量 属性 */
//页面loading
const loading = ref(true)

//定位城市
const locationCity = reactive({
  cityName: '',
  cityId: '',
  siteOID: '',
  siteCityOID: '',
  locationCityOID: '',
  locationCityName: '',
})

//当前城市
const currentCity = computed(() => store.currentCity)

// 控制弹窗广告显示
const showPopUpAd = ref(false)

// 搜索推荐词
const artistKeyword = ref('')

// 品类
const categories = ref([])

// 顶部banner
const banners = ref([])

// 热门巡演
const popularTours = ref([])

//折扣尾票
const disCounts = ref([])

/* 计算属性 */
//当前定位 或者手动设定的城市名字
const currentPosition = computed(() => {
  return store.currentCity.cityName
})

const modules = ref(Pagination)

const onSwiper = (swiper) => {
  // console.log('swiper', swiper)
}

const onSlideChange = () => {
  // console.log('slide change')
}

/* 生命周期 */
onMounted(async () => {
  loading.value = true
  // 检查路由来源，如果不是从 CityList 页面返回，则执行定位
  if (!route.query.from || route.query.from !== 'CityList') {
    await getLocation() //定位
  }

  await getSearchHot(currentCity.value.cityId)

  await getHomeData(currentCity.value.cityId)

  loading.value = false
})

/* 方法 */
// 定位
const getLocation = async () => {
  const res = await fetchLocation()
  // console.log(res)
  if (res.statusCode === 200) {
    locationCity.cityName = res.result?.data?.locationCityName
    locationCity.cityId = res.result?.data?.locationCityOID
    locationCity.siteOID = res.result?.data?.siteOID
    locationCity.siteCityOID = res.result?.data?.siteCityOID
    locationCity.locationCityOID = res.result?.data?.locationCityOID
    locationCity.locationCityName = res.result?.data?.locationCityName

    // 设置定位城市是当前访问城市
    store.setCurrentCity(locationCity.cityName, locationCity.cityId)

    //定位城市同步保存到store
    store.setLocationCity(
      locationCity.cityName,
      locationCity.cityId,
      locationCity.siteOID,
      locationCity.siteCityOID,
      locationCity.locationCityOID,
      locationCity.locationCityName,
    )
    // 当前定位城市放入最近访问
    store.unshiftHistoryCities({ cityName: locationCity.cityName, cityId: locationCity.cityId })
  }
}

// 顶部搜索框推荐词
const getSearchHot = async (cityId) => {
  const { statusCode, data } = await fetchSearchHot(cityId)

  if (statusCode == 200) {
    artistKeyword.value = data[0].keyword
  }
}

const getShowType = (id) => {
  // 使用 find() 找到第一个匹配的分类对象
  const category = store.categoryIcons?.find((category) => category.id === id)
  // 返回该分类对象的 showType 属性
  return category ? category.showType : 0
}

const getHomeData = async (cityId) => {
  const { statusCode, data } = await fetchHomeData(cityId)

  if (statusCode == 200) {
    // data[X]?.rooms[0]?.type ='CATEGORY'

    // 顶部分类
    categories.value = data.filter(
      (dataItem) => dataItem.rooms[0].type === 'CATEGORY',
    )[0]?.rooms[0].items

    console.log(' 首页 顶部分类categories', categories.value)

    // 顶部banner
    banners.value = data.filter(
      (dataItem) => dataItem.rooms[0].type === 'BANNER',
    )[0]?.rooms[0].items

    // 热门巡演
    popularTours.value = data.find((dataItem) => dataItem.title === '热门巡演')

    //折扣尾票
    disCounts.value = data.find((dataItem) => dataItem.title === '折扣尾票')
  }
}

//关闭弹窗广告
const closeDialog = (bool) => {
  // console.log('关闭纸弹窗广告', bool)
  showPopUpAd.value = bool
}

// const gotoPage = (type) => {
//   if (type === 'search') {
//     router.push({ path: '/search' })
//   }
// }

const goToCategory = (id, index) => {
  // 获取当前分类 showType
  const showType = getShowType(id)

  // store.setCurrentCategory(id, index)
  store.setCurrentCategoryIndex(index)

  console.log(`当前分类id:${id},当前分类showType:${showType}`)
  router.push({ path: '/category', query: { showType: showType } })
};
</script>

<style scoped lang="scss">
.container {
  position: relative;
  min-height: 100vh;

  scrollbar-width: none;

  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
    /* Chrome Safari */
  }

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .sticky-content {
    background-color: #fff; // 添加白色背景
    width: 100%;

    .categories {
      background-color: #fff;
      overflow-x: auto;
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: flex-start;
      padding: 0 15px 10px;
      gap: 10px;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      /* IE 10+ */

      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      .category {
        flex: 0 0 auto;
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: flex-start;
        text-align: center;
        border-radius: 100px;
        box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.08);
        padding: 8px 10px;

        p {
          font-size: 14px;
          font-weight: 500;
          margin: 0 0 0 5px; // 图片和文字之间的间距
          white-space: nowrap; // 防止文字换行
        }
      }
    }
  }

  .banner-wrapper {
    padding: 10px 15px;
    overflow: hidden;

    .banner {
      :deep(.swiper) {
        width: 100%;
        height: auto;
      }

      :deep(.swiper-slide) {
        width: 100%;
      }

      .thumb {
        border-radius: 10px;
        width: 100%;
        height: auto; // 保持图片的宽高比
        display: block; // 防止图片下方出现空白
      }
    }
  }

  .popularTours {
    margin-top: 20px;
    padding: 0 15px;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 18px;
      color: #000;
      font-weight: 600;

      .left {
        display: flex;
        align-items: center;

        .title {
          margin-right: 10px;
        }

        .iconHotTour {
          width: 50px;
        }
      }
    }

    .list {
      margin-top: 10px;

      ul.tour-list {
        list-style: none;
        display: flex;
        align-items: flex-start;
        justify-content: flex-start;
        overflow-x: auto;
        gap: 10px;

        scrollbar-width: none;
        /* Firefox */
        -ms-overflow-style: none;
        /* IE 10+ */

        &::-webkit-scrollbar {
          display: none;
          /* Chrome Safari */
        }

        li.tour-list-item {
          display: flex;
          flex-direction: column;

          .thumb-container {
            position: relative;
            overflow: hidden;
            width: 120px;
            height: 160px;

            .thumb {
              width: 100%;
              height: 100%;
            }

            .show-tag {
              position: absolute;
              left: 0;
              bottom: 5px;
            }
          }

          .tour-title {
            display: -webkit-box; // 使用弹性盒子布局
            -webkit-line-clamp: 2; // 限制显示2行
            -webkit-box-orient: vertical; // 垂直排列
            overflow: hidden; // 超出部分隐藏
            text-overflow: ellipsis; // 超出部分用省略号表示
            font-size: 16px;
            font-weight: 500;
            width: 120px;
            word-wrap: break-word; // 允许长单词换行
            margin-top: 5px;
          }
        }
      }
    }
  }

  ///////////////////////////////
  // 弹窗
  // .popup-container {
  //   display: flex;
  //   flex-direction: column;
  //   align-items: center;
  //   justify-content: center;

  //   .close {
  //     margin-top: 20px;
  //   }
  // }

  // 弹窗背景色透明
  :deep(.van-popup.van-popup--center.van-dialog) {
    background: transparent;
  }
}

:deep(.van-field__placeholder)::before {
  /*修改 placeholder 样式，将搜索图标放在文本左侧*/
  font-family: 'vant-icon';
  content: '\e663';
  /* search 图标的 Unicode 码 */
  margin-right: 6px;
  font-size: 14px;
  vertical-align: middle;
}

:deep(.van-field__placeholder) {
  /* 确保 placeholder 文本垂直居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
